import logging
import logging.config
import os
import sys

from openai import OpenAI

from funcall import funcall_log
from conf.config import AppConf

# 使用 pyinstaller 打包后,路径不对,使用该方式获取可用的配置文件目录 start
if getattr(sys, 'frozen', False):
    absPath = os.path.dirname(os.path.abspath(sys.executable))
elif __file__:
    absPath = os.path.dirname(os.path.abspath(__file__))
logsdir = absPath + os.sep + "logs"
print(f"logsdir={logsdir}")
if not os.path.exists(logsdir):  # 检查logs目录是否存在
    os.makedirs(logsdir)  # 如果不存在则创建logs目录

# '读取日志配置文件'
# logging.fileConfig('./logging.conf')
fname='./logging.conf'
# logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)
# 打开文件并指定使用 UTF-8 编码
with open(fname, 'r', encoding='utf-8') as f:
    logging.config.fileConfig(f, defaults=None, disable_existing_loggers=True)

funcall_log.setLevel(logging.DEBUG)


base_url=AppConf['ai']['base_url']
api_key=AppConf['ai']['api_key']
model=AppConf['ai']['model']

client = OpenAI(
    base_url=base_url,
    api_key=api_key
)

response=client.chat.completions.create(
    model=model,
    messages=[{"role":"user", "content":"你好，能帮我介绍一下杭州吗？"}],
    stream=True
)

if __name__ == '__main__':
    #免得比较卡
    #差不多是字典转对象的意思
    for chunk in response:
        #一个字一个字的输出
        print(chunk.choices[0].delta.content, end='', flush=True)
    res_choice = response['choices'][0]
    assistant_output = res_choice['message']
    print(f"\n大模型输出信息：{assistant_output}\n")